import db from '../config/database.js'

/**
 * 获取用户所有联系人
 */
export const getContacts = async (req, res) => {
  try {
    const userId = req.user.id

    const [contacts] = await db.execute(
      'SELECT * FROM contacts WHERE user_id = ? ORDER BY created_at DESC',
      [userId]
    )

    res.json({
      success: true,
      data: contacts
    })
  } catch (error) {
    console.error('获取联系人错误:', error)
    res.status(500).json({
      success: false,
      error: '服务器错误'
    })
  }
}

/**
 * 获取单个联系人
 */
export const getContact = async (req, res) => {
  try {
    const userId = req.user.id
    const {id} = req.params

    const [contacts] = await db.execute(
      'SELECT * FROM contacts WHERE id = ? AND user_id = ?',
      [id, userId]
    )

    if (contacts.length === 0) {
      return res.status(404).json({
        success: false,
        error: '联系人不存在'
      })
    }

    res.json({
      success: true,
      data: contacts[0]
    })
  } catch (error) {
    console.error('获取联系人错误:', error)
    res.status(500).json({
      success: false,
      error: '服务器错误'
    })
  }
}

/**
 * 创建联系人
 */
export const createContact = async (req, res) => {
  const connection = await db.getConnection()

  try {
    const userId = req.user.id
    const {name, phone, id_card, is_default = false} = req.body

    // 验证必填字段
    if (!name || !phone || !id_card) {
      return res.status(400).json({
        success: false,
        error: '姓名、手机号和身份证号为必填项'
      })
    }

    await connection.beginTransaction()

    // 如果设置为默认，先取消其他默认联系人
    if (is_default) {
      await connection.execute('UPDATE contacts SET is_default = 0 WHERE user_id = ? AND is_default = 1', [
        userId
      ])
    }

    // 创建联系人
    const [result] = await connection.execute(
      'INSERT INTO contacts (user_id, name, phone, id_card, is_default) VALUES (?, ?, ?, ?, ?)',
      [userId, name, phone, id_card, is_default ? 1 : 0]
    )

    // 获取新创建的联系人
    const [contacts] = await connection.execute('SELECT * FROM contacts WHERE id = ?', [result.insertId])

    await connection.commit()

    res.status(201).json({
      success: true,
      data: contacts[0]
    })
  } catch (error) {
    await connection.rollback()
    console.error('创建联系人错误:', error)
    res.status(500).json({
      success: false,
      error: '服务器错误'
    })
  } finally {
    connection.release()
  }
}

/**
 * 更新联系人
 */
export const updateContact = async (req, res) => {
  const connection = await db.getConnection()

  try {
    const userId = req.user.id
    const {id} = req.params
    const {name, phone, id_card, is_default} = req.body

    // 验证联系人是否存在且属于当前用户
    const [existingContacts] = await connection.execute(
      'SELECT * FROM contacts WHERE id = ? AND user_id = ?',
      [id, userId]
    )

    if (existingContacts.length === 0) {
      return res.status(404).json({
        success: false,
        error: '联系人不存在'
      })
    }

    await connection.beginTransaction()

    // 如果设置为默认，先取消其他默认联系人
    if (is_default) {
      await connection.execute(
        'UPDATE contacts SET is_default = 0 WHERE user_id = ? AND is_default = 1 AND id != ?',
        [userId, id]
      )
    }

    // 构建更新SQL
    const updates = []
    const params = []

    if (name !== undefined) {
      updates.push('name = ?')
      params.push(name)
    }
    if (phone !== undefined) {
      updates.push('phone = ?')
      params.push(phone)
    }
    if (id_card !== undefined) {
      updates.push('id_card = ?')
      params.push(id_card)
    }
    if (is_default !== undefined) {
      updates.push('is_default = ?')
      params.push(is_default ? 1 : 0)
    }

    if (updates.length > 0) {
      params.push(id, userId)
      await connection.execute(
        `UPDATE contacts SET ${updates.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND user_id = ?`,
        params
      )
    }

    // 获取更新后的联系人
    const [contacts] = await connection.execute('SELECT * FROM contacts WHERE id = ?', [id])

    await connection.commit()

    res.json({
      success: true,
      data: contacts[0]
    })
  } catch (error) {
    await connection.rollback()
    console.error('更新联系人错误:', error)
    res.status(500).json({
      success: false,
      error: '服务器错误'
    })
  } finally {
    connection.release()
  }
}

/**
 * 删除联系人
 */
export const deleteContact = async (req, res) => {
  try {
    const userId = req.user.id
    const {id} = req.params

    // 验证联系人是否存在且属于当前用户
    const [existingContacts] = await db.execute('SELECT * FROM contacts WHERE id = ? AND user_id = ?', [
      id,
      userId
    ])

    if (existingContacts.length === 0) {
      return res.status(404).json({
        success: false,
        error: '联系人不存在'
      })
    }

    // 删除联系人
    await db.execute('DELETE FROM contacts WHERE id = ? AND user_id = ?', [id, userId])

    res.json({
      success: true,
      message: '删除成功'
    })
  } catch (error) {
    console.error('删除联系人错误:', error)
    res.status(500).json({
      success: false,
      error: '服务器错误'
    })
  }
}

/**
 * 设置默认联系人
 */
export const setDefaultContact = async (req, res) => {
  const connection = await db.getConnection()

  try {
    const userId = req.user.id
    const {id} = req.params

    // 验证联系人是否存在且属于当前用户
    const [existingContacts] = await connection.execute(
      'SELECT * FROM contacts WHERE id = ? AND user_id = ?',
      [id, userId]
    )

    if (existingContacts.length === 0) {
      return res.status(404).json({
        success: false,
        error: '联系人不存在'
      })
    }

    await connection.beginTransaction()

    // 先取消所有默认联系人
    await connection.execute('UPDATE contacts SET is_default = 0 WHERE user_id = ? AND is_default = 1', [
      userId
    ])

    // 设置当前联系人为默认
    await connection.execute(
      'UPDATE contacts SET is_default = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND user_id = ?',
      [id, userId]
    )

    // 获取更新后的联系人
    const [contacts] = await connection.execute('SELECT * FROM contacts WHERE id = ?', [id])

    await connection.commit()

    res.json({
      success: true,
      data: contacts[0]
    })
  } catch (error) {
    await connection.rollback()
    console.error('设置默认联系人错误:', error)
    res.status(500).json({
      success: false,
      error: '服务器错误'
    })
  } finally {
    connection.release()
  }
}
